package com.teamone.mobilewatch.xml;

import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;

/**
 * 
 * Processes xml string containing single boolean tag
 * 
 */
public class SingleTagXmlProcessorImpl implements XmlProcessor<Boolean> {
	private static final String TAG = "SingleTagXmlProcessorImpl";
	private final static String BOOL_TAG = "boolean";

	private static SingleTagXmlProcessorImpl instance;

	private XmlPullParserFactory factory;
	private XmlPullParser xpp;

	/**
	 * Constructs object
	 * 
	 * @throws XmlPullParserException
	 */
	private SingleTagXmlProcessorImpl() throws XmlPullParserException {
		factory = XmlPullParserFactory.newInstance();
		factory.setNamespaceAware(true);
		xpp = factory.newPullParser();
	}

	/**
	 * Returns instance of the class
	 * 
	 * @throws XmlPullParserException
	 */
	public static synchronized SingleTagXmlProcessorImpl getInstance()
			throws XmlPullParserException {
		if (null == instance) {
			instance = new SingleTagXmlProcessorImpl();
		}
		return instance;
	}

	/**
	 * Processes xml string
	 * 
	 * @return - boolean value of the boolean tag in xml string
	 */
	@Override
	public Boolean process(String xmlString) throws IOException,
			XmlPullParserException, ParseException {

		Boolean response = false;

		try {
			xpp.setInput(new StringReader(xmlString));

			int eventType;
			eventType = xpp.getEventType();
			boolean stopParsing = false;

			while (eventType != XmlPullParser.END_DOCUMENT) {
				// ->boolean
				if (eventType == XmlPullParser.START_TAG
						&& BOOL_TAG.equals(xpp.getName())) {
					Log.d(TAG, "parsing tag:" + xpp.getName());
					// get the value of the tag
					eventType = xpp.next();
					if (eventType == XmlPullParser.TEXT) {
						String text = xpp.getText();
						Log.d(TAG, "parsed value of <boolean> tag:" + text);
						response = Boolean.valueOf(text);
						return response;
					}
				}
				eventType = xpp.next();
				Log.d(TAG, "next parsing event:" + eventType);
			} // end while

		} catch (IOException e) {
			Log.e("XmlProcessor", e.getMessage());
			throw e;
		} catch (XmlPullParserException e1) {
			Log.e("XmlProcessor", e1.getMessage());
			throw e1;
		}
		return response;
	}
}
